package com.peter.smv.base.base

import android.os.Bundle
import android.view.LayoutInflater
import androidx.appcompat.app.AppCompatActivity
import androidx.viewbinding.ViewBinding
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.cancel
import java.lang.reflect.ParameterizedType

abstract class AbsActivity<VB : ViewBinding> : AppCompatActivity(), CoroutineScope by MainScope() {

    var isVisibleToUser = false
    lateinit var mViewBinding: VB

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val type = javaClass.genericSuperclass
        if (type is ParameterizedType) {
            val clazz = type.actualTypeArguments[0] as Class<*>
            val method = clazz.getMethod("inflate", LayoutInflater::class.java)
            mViewBinding = method.invoke(null, layoutInflater) as VB
            setContentView(mViewBinding.root)
        }
        initView()
        startData()
    }

    abstract fun initView()
    abstract fun startData()

    override fun onWindowFocusChanged(hasFocus: Boolean) {
        super.onWindowFocusChanged(hasFocus)
        isVisibleToUser = hasFocus
    }

    override fun onDestroy() {
        super.onDestroy()
        cancel()
    }
}